import CryptoJS from "crypto-js";
import config from "@/config";

// 日期格式化
export function parseTime(time, pattern) {
	if (arguments.length === 0 || !time) {
		return null
	}
	const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
			time = parseInt(time)
		} else if (typeof time === 'string') {
			time = time.replace(new RegExp(/-/gm), '/');
		}
		if ((typeof time === 'number') && (time.toString().length === 10)) {
			time = time * 1000
		}
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') {
			return ['日', '一', '二', '三', '四', '五', '六'][value]
		}
		if (result.length > 0 && value < 10) {
			value = '0' + value
		}
		return value || 0
	})
	return time_str
}

// 前往页面
export function handleToPage(url) {
	if (!url) {
		uni.showToast({
			title: "正在开发中",
			icon: "none"
		})
		return;
	}
	uni.navigateTo({
		url: url
	})
}

// 点击拨打电话
export function handleCallPhone(phone) {
	if (!phone) {
		uni.showToast({
			title: "未获取到电话信息",
			icon: "none"
		})
		return;
	}
	uni.makePhoneCall({
		phoneNumber: phone
	})
}

// 打开导航
export function handleNavigation(name, latitude, longitude) {
	uni.openLocation({
		latitude: Number(latitude),
		longitude: Number(longitude),
		name: name
	});
}

// 生成随机字符串
export function generateRandomString(length) {
	let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	let randomString = '';
	for (let i = 0; i < length; i++) {
		randomString += characters.charAt(Math.floor(Math.random() * characters.length));
	}
	return randomString;
}

// 参数排序并转换成&连接
export function sortQueryParams(query) {
	const sortedParams = Object.keys(query).sort();
	const sortedQueryString = sortedParams.map(param => `${param}=${query[param]}`).join('&');
	return sortedQueryString;
}

// 接口加签
export function getApiSignData(params) {
	params = {
		...params,
		app_id: config.signAppId,
		timeStamp: Number(Date.now().toString().substring(0, 10)),
		nonceStr: generateRandomString(32)
	}
	// 参数排序并转成&连接
	let sign = sortQueryParams(params) + `&key=${config.signKey}`;
	// encodeURIComponent
	sign = encodeURIComponent(sign);
	// MD5加密
	sign = CryptoJS.MD5(sign).toString();
	// 转大写
	sign = sign.toUpperCase();
	params.sign = sign;
	return params;
}

// 打开微信授权设置
export function openSetting() {
	return new Promise((resolve, reject) => {
		uni.getSetting({
			success: (res) => {
				const status = res.authSetting
				if (!status['scope.userLocation']) {
					// 如果授权信息中没有地理位置的授权，则需要弹窗提示用户需要授权地理信息
					uni.showModal({
						title: '温馨提示',
						content: '需要获取您的地理位置，请确认授权',
						success: (tip) => {
							if (tip.confirm) {
								// 如果用户同意授权地理信息，则打开授权设置页面
								uni.openSetting({
									success: (data) => {
										resolve()
									},
								})
							} else {
								const pages = getCurrentPages();
								const prevPage = pages[pages.length - 2];
								if (prevPage) {
									// 如果不同意授权地理信息，则返回上一页面
									uni.navigateBack({
										delta: 1
									})
								} else {
									// 没有上一页则返回首页
									uni.reLaunch({
										url: "/pages/home/index"
									})
								}
							}
						}
					})
				}
			}
		})
	})
}

// 距离单位转换
export function formatDistance(distance) {
	if (distance < 1000) {
		return distance + "m";
	} else {
		return (distance / 1000).toFixed(1) + "km";
	}
}

// 未登录提示
export function showNotLoginModal() {
	uni.showModal({
		title: "温馨提示",
		content: "您还没有登录，是否立即前往登录？",
		showCancel: true,
		confirmText: "立即前往",
		confirmColor: "#3377FF",
		cancelText: "再看看",
		cancelColor: "#999999",
		success: (result) => {
			if(result.confirm) {
				uni.navigateTo({
					url: "/pages/user/login"
				})
			}
		}
	})
}